<?php
declare(strict_types=1);

namespace app\controller;

use app\BaseController;
use think\facade\Db;
use think\facade\Request;
use think\facade\Validate;

/**
 * 供应商模块控制器
 */
class Supplier extends BaseController
{
    /**
     * 获取供应商列表
     */
    public function getSupplierList()
    {
        $page = Request::param('page', 1);
        $limit = Request::param('limit', 10);
        $search = Request::param('search', '');
        $level = Request::param('level', '');
        $status = Request::param('status', '');
        
        // 记录请求参数
        file_put_contents(__DIR__ . '/log250825/supplier_list.log', date('Y-m-d H:i:s') . ' - 请求参数: ' . json_encode([
            'page' => $page,
            'limit' => $limit,
            'search' => $search,
            'level' => $level,
            'status' => $status
        ], JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
        
        $where = [];
        if (!empty($search)) {
            $where[] = ['supplier_name|contact_person|phone', 'like', "%{$search}%"];
        }
        
        if ($level !== '') {
            $where[] = ['level', '=', $level];
        }
        
        if ($status !== '') {
            $where[] = ['status', '=', $status];
        }
        
        try {
            $count = Db::name('supplier')->where($where)->count();
            $list = Db::name('supplier')
                ->where($where)
                ->page((int)$page, (int)$limit)
                ->order('id', 'desc')
                ->select()
                ->toArray();
            
            // 记录查询结果
            file_put_contents(__DIR__ . '/log250825/supplier_list.log', date('Y-m-d H:i:s') . ' - 查询结果: 总数=' . $count . ', 列表条数=' . count($list) . PHP_EOL, FILE_APPEND);
            if (count($list) > 0) {
                file_put_contents(__DIR__ . '/log250825/supplier_list.log', date('Y-m-d H:i:s') . ' - 第一条数据: ' . json_encode($list[0], JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
            } else {
                file_put_contents(__DIR__ . '/log250825/supplier_list.log', date('Y-m-d H:i:s') . ' - 没有数据' . PHP_EOL, FILE_APPEND);
            }
            
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } catch (\Exception $e) {
            file_put_contents(__DIR__ . '/log250825/supplier_list.log', date('Y-m-d H:i:s') . ' - 查询异常: ' . $e->getMessage() . PHP_EOL, FILE_APPEND);
            return json(['code' => 400, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 添加供应商
     */
    public function addSupplier()
    {
        $data = Request::post();
        
        $validate = Validate::rule([
            'supplier_name' => 'require',
            'contact_person' => 'require',
            'phone' => 'require',
            'level' => 'require',
            'status' => 'require|number',
        ]);
        
        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }
        
        // 检查供应商名称是否已存在
        $exists = Db::name('supplier')
            ->where('supplier_name', $data['supplier_name'])
            ->find();
            
        if ($exists) {
            return json(['code' => 400, 'msg' => '供应商名称已存在']);
        }
        
        $data['create_time'] = date('Y-m-d H:i:s');
        $data['update_time'] = date('Y-m-d H:i:s'); // 添加更新时间字段
        
        // 记录日志，查看提交的数据
        file_put_contents(__DIR__ . '/log250825/supplier_add.log', date('Y-m-d H:i:s') . ' - ' . json_encode($data, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
        
        try {
            $id = Db::name('supplier')->insertGetId($data);
            
            if ($id) {
                // 记录成功日志
                file_put_contents(__DIR__ . '/log250825/supplier_add.log', date('Y-m-d H:i:s') . ' - 添加成功，ID: ' . $id . PHP_EOL, FILE_APPEND);
                
                // 获取新增的供应商数据
                $newSupplier = Db::name('supplier')->where('id', $id)->find();
                
                return json(['code' => 200, 'msg' => '添加成功', 'data' => $newSupplier]);
            } else {
                file_put_contents(__DIR__ . '/log250825/supplier_add.log', date('Y-m-d H:i:s') . ' - 添加失败，无ID返回' . PHP_EOL, FILE_APPEND);
                return json(['code' => 400, 'msg' => '添加失败']);
            }
        } catch (\Exception $e) {
            file_put_contents(__DIR__ . '/log250825/supplier_add.log', date('Y-m-d H:i:s') . ' - 添加异常: ' . $e->getMessage() . PHP_EOL, FILE_APPEND);
            return json(['code' => 400, 'msg' => '添加失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 更新供应商
     */
    public function updateSupplier()
    {
        $data = Request::post();
        
        $validate = Validate::rule([
            'id' => 'require|number',
            'supplier_name' => 'require',
            'contact_person' => 'require',
            'phone' => 'require',
            'level' => 'require',
            'status' => 'require|number',
        ]);
        
        if (!$validate->check($data)) {
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }
        
        // 检查供应商名称是否已存在（排除自身）
        $exists = Db::name('supplier')
            ->where('supplier_name', $data['supplier_name'])
            ->where('id', '<>', $data['id'])
            ->find();
            
        if ($exists) {
            return json(['code' => 400, 'msg' => '供应商名称已存在']);
        }
        
        $data['update_time'] = date('Y-m-d H:i:s');
        $result = Db::name('supplier')->update($data);
        
        if ($result) {
            return json(['code' => 200, 'msg' => '更新成功']);
        } else {
            return json(['code' => 400, 'msg' => '更新失败']);
        }
    }
    
    /**
     * 删除供应商
     */
    public function deleteSupplier()
    {
        $id = Request::param('id');
        
        if (empty($id)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        // 检查是否有关联数据
        $hasPayable = Db::name('finance_payable')
            ->where('supplier_id', $id)
            ->find();
            
        if ($hasPayable) {
            return json(['code' => 400, 'msg' => '该供应商有关联的应付款项，无法删除']);
        }
        
        $hasPayment = Db::name('finance_payment')
            ->where('supplier_id', $id)
            ->find();
            
        if ($hasPayment) {
            return json(['code' => 400, 'msg' => '该供应商有关联的付款单，无法删除']);
        }
        
        $result = Db::name('supplier')->delete($id);
        
        if ($result) {
            return json(['code' => 200, 'msg' => '删除成功']);
        } else {
            return json(['code' => 400, 'msg' => '删除失败']);
        }
    }
    
    /**
     * 获取供应商详情
     */
    public function getSupplierDetail()
    {
        $id = Request::param('id');
        
        if (empty($id)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        $supplier = Db::name('supplier')->where('id', $id)->find();
        
        if (!$supplier) {
            return json(['code' => 400, 'msg' => '供应商不存在']);
        }
        
        return json(['code' => 200, 'msg' => '获取成功', 'data' => $supplier]);
    }
    
    /**
     * 获取供应商评估列表
     */
    public function getEvaluationList()
    {
        $page = Request::param('page', 1);
        $limit = Request::param('limit', 10);
        $search = Request::param('search', '');
        $supplier_id = Request::param('supplier_id', '');
        $start_date = Request::param('start_date', '');
        $end_date = Request::param('end_date', '');

        $where = [];
        if (!empty($search)) {
            $supplierIds = Db::name('supplier')
                ->where('supplier_name', 'like', "%{$search}%")
                ->column('id');
            if (!empty($supplierIds)) {
                $where[] = ['supplier_id', 'in', $supplierIds];
            }
        }
        
        if ($supplier_id !== '') {
            $where[] = ['supplier_id', '=', $supplier_id];
        }
        
        // 添加日期范围查询
        if (!empty($start_date) && !empty($end_date)) {
            $where[] = ['evaluation_date', 'between', [$start_date, $end_date]];
        }
        
        try {
            $count = Db::name('supplier_evaluation')->where($where)->count();
            $list = Db::name('supplier_evaluation')
                ->where($where)
                ->page((int)$page, (int)$limit)
                ->order('id', 'desc')
                ->select()
                ->toArray();
                
            // 记录查询结果
            file_put_contents(__DIR__ . '/log250825/evaluation_list.log', date('Y-m-d H:i:s') . ' - 查询结果: 总数=' . $count . ', 列表条数=' . count($list) . PHP_EOL, FILE_APPEND);
            if (count($list) > 0) {
                file_put_contents(__DIR__ . '/log250825/evaluation_list.log', date('Y-m-d H:i:s') . ' - 第一条数据: ' . json_encode($list[0], JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
            } else {
                file_put_contents(__DIR__ . '/log250825/evaluation_list.log', date('Y-m-d H:i:s') . ' - 没有数据' . PHP_EOL, FILE_APPEND);
            }
            
            // 关联供应商和评估人信息
            foreach ($list as &$item) {
                $supplier = Db::name('supplier')->where('id', $item['supplier_id'])->find();
                $evaluator = Db::name('user')->where('id', $item['evaluator_id'])->find();
                $item['supplier_name'] = $supplier ? $supplier['supplier_name'] : '';
                $item['evaluator_name'] = $evaluator ? $evaluator['realname'] : '';
            }
            
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } catch (\Exception $e) {
            file_put_contents(__DIR__ . '/log250825/evaluation_list.log', date('Y-m-d H:i:s') . ' - 查询异常: ' . $e->getMessage() . PHP_EOL, FILE_APPEND);
            return json(['code' => 400, 'msg' => '获取失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 添加供应商评估
     */
    public function addEvaluation()
    {
        $data = Request::post();
        
        // 记录请求数据
        file_put_contents(__DIR__ . '/log250825/evaluation_add.log', date('Y-m-d H:i:s') . ' - 请求数据: ' . json_encode($data, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
        
        $validate = Validate::rule([
            'supplier_id' => 'require|number',
            'evaluation_date' => 'require|date',
            'quality_score' => 'require|float|between:0,100',
            'delivery_score' => 'require|float|between:0,100',
            'price_score' => 'require|float|between:0,100',
            'service_score' => 'require|float|between:0,100',
            'evaluator_id' => 'require|number',
        ]);
        
        if (!$validate->check($data)) {
            file_put_contents(__DIR__ . '/log250825/evaluation_add.log', date('Y-m-d H:i:s') . ' - 验证失败: ' . $validate->getError() . PHP_EOL, FILE_APPEND);
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }
        
        try {
            // 过滤掉不存在的字段
            $allowedFields = [
                'supplier_id', 'evaluation_date', 'quality_score', 'delivery_score', 
                'price_score', 'service_score', 'total_score', 'evaluator_id', 'remark', 
                'create_time', 'update_time'
            ];
            
            $filteredData = [];
            foreach ($allowedFields as $field) {
                if (isset($data[$field])) {
                    $filteredData[$field] = $data[$field];
                }
            }
            
            // 确保数值字段为数值类型
            $filteredData['supplier_id'] = (int)$filteredData['supplier_id'];
            $filteredData['quality_score'] = (float)$filteredData['quality_score'];
            $filteredData['delivery_score'] = (float)$filteredData['delivery_score'];
            $filteredData['price_score'] = (float)$filteredData['price_score'];
            $filteredData['service_score'] = (float)$filteredData['service_score'];
            $filteredData['evaluator_id'] = (int)$filteredData['evaluator_id'];
            
            // 计算总分
            $filteredData['total_score'] = ($filteredData['quality_score'] + $filteredData['delivery_score'] + $filteredData['price_score'] + $filteredData['service_score']) / 4;
            $filteredData['create_time'] = date('Y-m-d H:i:s');
            $filteredData['update_time'] = date('Y-m-d H:i:s');
            
            // 记录处理后的数据
            file_put_contents(__DIR__ . '/log250825/evaluation_add.log', date('Y-m-d H:i:s') . ' - 过滤后数据: ' . json_encode($filteredData, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
            
            $id = Db::name('supplier_evaluation')->insertGetId($filteredData);
            
            if ($id) {
                file_put_contents(__DIR__ . '/log250825/evaluation_add.log', date('Y-m-d H:i:s') . ' - 添加成功，ID: ' . $id . PHP_EOL, FILE_APPEND);
                
                // 获取新增的评估记录
                $newEvaluation = Db::name('supplier_evaluation')->where('id', $id)->find();
                
                // 关联供应商和评估人信息
                $supplier = Db::name('supplier')->where('id', $newEvaluation['supplier_id'])->find();
                $evaluator = Db::name('user')->where('id', $newEvaluation['evaluator_id'])->find();
                $newEvaluation['supplier_name'] = $supplier ? $supplier['supplier_name'] : '';
                $newEvaluation['evaluator_name'] = $evaluator ? $evaluator['realname'] : '';
                
                return json(['code' => 200, 'msg' => '添加成功', 'data' => $newEvaluation]);
            } else {
                file_put_contents(__DIR__ . '/log250825/evaluation_add.log', date('Y-m-d H:i:s') . ' - 添加失败，无ID返回' . PHP_EOL, FILE_APPEND);
                return json(['code' => 400, 'msg' => '添加失败']);
            }
        } catch (\Exception $e) {
            file_put_contents(__DIR__ . '/log250825/evaluation_add.log', date('Y-m-d H:i:s') . ' - 添加异常: ' . $e->getMessage() . PHP_EOL, FILE_APPEND);
            return json(['code' => 400, 'msg' => '添加失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 更新供应商评估
     */
    public function updateEvaluation()
    {
        $data = Request::post();
        
        // 记录请求数据
        file_put_contents(__DIR__ . '/log250825/evaluation_update.log', date('Y-m-d H:i:s') . ' - 请求数据: ' . json_encode($data, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
        
        $validate = Validate::rule([
            'id' => 'require|number',
            'supplier_id' => 'require|number',
            'evaluation_date' => 'require|date',
            'quality_score' => 'require|float|between:0,100',
            'delivery_score' => 'require|float|between:0,100',
            'price_score' => 'require|float|between:0,100',
            'service_score' => 'require|float|between:0,100',
            'evaluator_id' => 'require|number',
        ]);
        
        if (!$validate->check($data)) {
            file_put_contents(__DIR__ . '/log250825/evaluation_update.log', date('Y-m-d H:i:s') . ' - 验证失败: ' . $validate->getError() . PHP_EOL, FILE_APPEND);
            return json(['code' => 400, 'msg' => $validate->getError()]);
        }
        
        try {
            // 过滤掉不存在的字段
            $allowedFields = [
                'id', 'supplier_id', 'evaluation_date', 'quality_score', 'delivery_score', 
                'price_score', 'service_score', 'total_score', 'evaluator_id', 'remark', 'update_time'
            ];
            
            $filteredData = [];
            foreach ($allowedFields as $field) {
                if (isset($data[$field])) {
                    $filteredData[$field] = $data[$field];
                }
            }
            
            // 确保数值字段为数值类型
            $filteredData['id'] = (int)$filteredData['id'];
            $filteredData['supplier_id'] = (int)$filteredData['supplier_id'];
            $filteredData['quality_score'] = (float)$filteredData['quality_score'];
            $filteredData['delivery_score'] = (float)$filteredData['delivery_score'];
            $filteredData['price_score'] = (float)$filteredData['price_score'];
            $filteredData['service_score'] = (float)$filteredData['service_score'];
            $filteredData['evaluator_id'] = (int)$filteredData['evaluator_id'];
            
            // 计算总分
            $filteredData['total_score'] = ($filteredData['quality_score'] + $filteredData['delivery_score'] + $filteredData['price_score'] + $filteredData['service_score']) / 4;
            $filteredData['update_time'] = date('Y-m-d H:i:s');
            
            // 记录过滤后的数据
            file_put_contents(__DIR__ . '/log250825/evaluation_update.log', date('Y-m-d H:i:s') . ' - 过滤后数据: ' . json_encode($filteredData, JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
            
            $result = Db::name('supplier_evaluation')->update($filteredData);
            
            if ($result !== false) {
                file_put_contents(__DIR__ . '/log250825/evaluation_update.log', date('Y-m-d H:i:s') . ' - 更新成功，ID: ' . $filteredData['id'] . PHP_EOL, FILE_APPEND);
                
                // 获取更新后的评估记录
                $updatedEvaluation = Db::name('supplier_evaluation')->where('id', $filteredData['id'])->find();
                
                // 关联供应商和评估人信息
                $supplier = Db::name('supplier')->where('id', $updatedEvaluation['supplier_id'])->find();
                $evaluator = Db::name('user')->where('id', $updatedEvaluation['evaluator_id'])->find();
                $updatedEvaluation['supplier_name'] = $supplier ? $supplier['supplier_name'] : '';
                $updatedEvaluation['evaluator_name'] = $evaluator ? $evaluator['realname'] : '';
                
                return json(['code' => 200, 'msg' => '更新成功', 'data' => $updatedEvaluation]);
            } else {
                file_put_contents(__DIR__ . '/log250825/evaluation_update.log', date('Y-m-d H:i:s') . ' - 更新失败' . PHP_EOL, FILE_APPEND);
                return json(['code' => 400, 'msg' => '更新失败']);
            }
        } catch (\Exception $e) {
            file_put_contents(__DIR__ . '/log250825/evaluation_update.log', date('Y-m-d H:i:s') . ' - 更新异常: ' . $e->getMessage() . PHP_EOL, FILE_APPEND);
            return json(['code' => 400, 'msg' => '更新失败: ' . $e->getMessage()]);
        }
    }
    
    /**
     * 删除供应商评估
     */
    public function deleteEvaluation()
    {
        $id = Request::param('id');
        
        if (empty($id)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        $result = Db::name('supplier_evaluation')->delete($id);
        
        if ($result) {
            return json(['code' => 200, 'msg' => '删除成功']);
        } else {
            return json(['code' => 400, 'msg' => '删除失败']);
        }
    }
    
    /**
     * 获取供应商评估详情
     */
    public function getEvaluationDetail()
    {
        $id = Request::param('id');
        
        if (empty($id)) {
            return json(['code' => 400, 'msg' => '参数错误']);
        }
        
        $evaluation = Db::name('supplier_evaluation')->where('id', $id)->find();
        
        if (!$evaluation) {
            return json(['code' => 400, 'msg' => '评估记录不存在']);
        }
        
        // 关联供应商和评估人信息
        $supplier = Db::name('supplier')->where('id', $evaluation['supplier_id'])->find();
        $evaluator = Db::name('user')->where('id', $evaluation['evaluator_id'])->find();
        $evaluation['supplier_name'] = $supplier ? $supplier['supplier_name'] : '';
        $evaluation['evaluator_name'] = $evaluator ? $evaluator['realname'] : '';
        
        return json(['code' => 200, 'msg' => '获取成功', 'data' => $evaluation]);
    }
    
    /**
     * 获取供应商统计数据
     */
    public function getSupplierStatistics()
    {
        // 供应商总数
        $supplierTotal = Db::name('supplier')->count();
        
        // 活跃供应商数（状态为正常的）
        $activeSupplierCount = Db::name('supplier')
            ->where('status', 1)
            ->count();
            
        // 供应商等级分布
        $levelDistribution = Db::name('supplier')
            ->field('level, COUNT(*) as count')
            ->group('level')
            ->select()
            ->toArray();
            
        // 评分最高的前5个供应商
        $topSuppliers = Db::name('supplier_evaluation')
            ->field('supplier_id, AVG(total_score) as avg_score')
            ->group('supplier_id')
            ->order('avg_score', 'desc')
            ->limit(5)
            ->select()
            ->toArray();
            
        // 关联供应商名称
        foreach ($topSuppliers as &$item) {
            $supplier = Db::name('supplier')->where('id', $item['supplier_id'])->find();
            $item['supplier_name'] = $supplier ? $supplier['supplier_name'] : '';
        }
        
        return json([
            'code' => 200, 
            'msg' => '获取成功', 
            'data' => [
                'supplier_total' => $supplierTotal,
                'active_supplier_count' => $activeSupplierCount,
                'level_distribution' => $levelDistribution,
                'top_suppliers' => $topSuppliers
            ]
        ]);
    }

    /**
     * 获取供应商列表（简化版，用于下拉选择）
     */
    public function getList()
    {
        try {
            $list = Db::name('supplier')
                ->where('status', 1)  // 只获取状态正常的供应商
                ->field('id, supplier_name')
                ->order('id', 'desc')
                ->select()
                ->toArray();
            
            return json([
                'code' => 200,
                'msg' => '获取成功',
                'data' => [
                    'list' => $list,
                    'total' => count($list)
                ]
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 400,
                'msg' => '获取失败: ' . $e->getMessage()
            ]);
        }
    }
}
